package com.white.hot.controller.alipay;

import java.io.IOException;
import java.io.PrintWriter;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import com.alipay.api.AlipayApiException;
import com.alipay.api.AlipayClient;
import com.alipay.api.DefaultAlipayClient;
import com.alipay.api.domain.GetRuleInfo;
import com.alipay.api.request.AlipayOpenPublicTemplateMessageIndustryModifyRequest;
import com.alipay.api.response.AlipayOpenPublicTemplateMessageIndustryModifyResponse;
import com.white.hot.controller.BaseController;
import com.white.hot.dto.resp.BaseResp;

@Controller
@RequestMapping("/alipay")
public class AlipayController extends BaseController
{

	private final String appId = "2016080400161858";
	// 支付宝私钥
	private final String RSA_PRIVATE = "MIIEvAIBADANBgkqhkiG9w0BAQEFAASCBKYwggSiAgEAAoIBAQCfxemzcrGgq0m1"+
										"33JrE/rpI+3JpnAImBHSXL1mvKY+o5dF7MdE61/ed2heI/MBbvgI74ngYIPcXhBe"+
										"rOJgFOKZaArJgPmhzRYXcHvDJ4Es4ukD+gof0p6MEV03zhC6nTSOo4wb7MSePers"+
										"QyK1sKiDvL/VuFLxBSYedBxIETy1y0JOKdZFrFnhTUcAUZ6Nv5sicQHfT+zNHupI"+
										"SHdwKX2ukueLVKvYeiv2eaw4yH0e/nnj4y8SE5sfdCKMrRt++m562YsvIqTY6TcU"+
										"OmZx6plf6xZ7cYnR3S2XgAn8P6iuLN4iLO5iBy26PfCJYziLNcu32aAiHRyuWziy"+
										"CuSKH0aNAgMBAAECggEAcV13bglSecMvwOl0AQAjR2tj3HHJCoAEHTQKe6wddVKU"+
										"ElxoI8Gyu2IUXr+5O+ol+gkk1l0FEsZ3bQXUdgI7qkfFZ6ao+aJQK393gUg1gsja"+
										"NyUiK+RA9PeZIfCHtDG5SgBHeMTt2a3rU4prRWm8mATERPvNdhCGNJOEQaphXkdk"+
										"mr6cPJHYHqA6J791e4StEs/zU+z8j/mD3Gkh1yUaAWy3H7pEnXHB8etEME7HvM0Z"+
										"EAxWihGCcqK3pmG1/ErpzMy1A/VenyO1wFKLIVcOcYmkk6uIu4Lkv6XB8BkVfNck"+
										"OIidiUNdQN97rt+PWoBSmF1NkdqjtS71nQMXdwMf4QKBgQDK+SJLOUggsEi/Zemw"+
										"J8xgaovth+TAp/F6MVH54T2UiSRacKi8enrUuQLpjutnsguy0EwXR5WYcZn5eEnW"+
										"e2O+Zm4ns+JNMQV/qq7hpE0+HR1hsyMPPSEDhjuRB6CKYr3yTI86qeeU2TgEpTNO"+
										"qDXC4uKv26IgHcVAkWg6EFULNQKBgQDJg42fsphELWjrVidnIPDadMqG3jf58tCh"+
										"kNw9cUl7lrQ9PhLjEIOt9fA9JC9jFcYD4DOxOGS3anpZ1AHeWLCAX25sSq0jvnK/"+
										"yR1Zvd/F6qLoXXAY49NbRqYwBc8Q343mI2aVP5B3+QcKnT6875p75iWmq010ezXy"+
										"mbExEVXg+QKBgGDDEklAPpVu1M+B+z0CTBlu0dRkI3aA2crB9m2kpmHIW29OI/Lu"+
										"hN4icTP88VaW96LAUHYMp1FsXtYiNTkty6g6VqtQw0K/avqo2QQy+qvw30/zQXSD"+
										"VNjERmNmem9ekWUQgHucAg3g3CbCxsnpwO9ukFj74Ldk2eNlLoX3wUM9AoGAfwn0"+
										"as1IuRJ3poV16coWjWI7m7LUTzsI1BJjBkk5LjTgBAvyFDwBB9aYUbNSPIEpiJ/7"+
										"dqo6tHboE2FYnDgFbai8EIEzjekupkG/wye0vy0g7qSZWtemE1ECzBudYuHMr115"+
										"+nVMOpZAHizrtGjJV3rMGbq85cYXSI4j6u8m2OECgYAtgJ6wjGsrEBiycrzaATOD"+
										"LeNFlHEIFOYiEhzCcOMq5yAZxextgsoCf7N24rO2Yossi/yvcw6Gl04KDGyBFe5y"+
										"dQmHQr3hC3AsWZlkiWSSPL/KlnrRwp568TWxAI8jgt90cktEqQjF87O7unRjhsZ+"+
										"AhFtGrcy7uQVufpkOzNcBw==";
	
	private final String RSA_PUBLIC = "MIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEAn8Xps3KxoKtJtd9yaxP6"+
										"6SPtyaZwCJgR0ly9ZrymPqOXRezHROtf3ndoXiPzAW74CO+J4GCD3F4QXqziYBTi"+
										"mWgKyYD5oc0WF3B7wyeBLOLpA/oKH9KejBFdN84Qup00jqOMG+zEnj3q7EMitbCo"+
										"g7y/1bhS8QUmHnQcSBE8tctCTinWRaxZ4U1HAFGejb+bInEB30/szR7qSEh3cCl9"+
										"rpLni1Sr2Hor9nmsOMh9Hv554+MvEhObH3QijK0bfvpuetmLLyKk2Ok3FDpmceqZ"+
										"X+sWe3GJ0d0tl4AJ/D+orizeIizuYgctuj3wiWM4izXLt9mgIh0crls4sgrkih9G"+
										"jQIDAQAB";
	//pid 商户ID可在支付宝后台查看
	private static final String PID = "2088102169848083";
	//seller 商户账户，就是付款给谁
	private static final String SELLER = "sardgh3660@sandbox.com";

	/***
	 * 构造请求支付的参数, 注意有个异步回调的接口，那里填写本web中的一个链接Controller
	 * 
	 * @param subject 商品名称
	 * @param body 商品详情描述
	 * @param price 价格（元为单位）
	 * @param request
	 * @return 返回完整的请求参数
	 */
	@RequestMapping("/getOrderInfo")
	@ResponseBody
	private Object getOrderInfo(
			@RequestParam(value = "body")    String body,
			@RequestParam(value = "subject") String subject,
			@RequestParam(value = "price")   String price,
			HttpServletRequest request)
	{
		BaseResp br = new BaseResp();
		String out_trade_no = getOutTradeNo20();
		String biz = "{\"body\":"+body+",\"subject\":"+subject
				+",\"out_trade_no\":"+out_trade_no+",\"total_amount\":"+price
				+",\"seller_id\":"+SELLER+",\"product_code\":QUICK_MSECURITY_PAY}";
		System.out.println(biz);
		
		AlipayClient alipayClient = new DefaultAlipayClient("https://openapi.alipay.com/gateway.do",appId,RSA_PRIVATE,"json","utf-8",RSA_PUBLIC,"RSA");
		AlipayOpenPublicTemplateMessageIndustryModifyRequest aliReq = new AlipayOpenPublicTemplateMessageIndustryModifyRequest();
		aliReq.setBizContent(biz);
		try
		{
			AlipayOpenPublicTemplateMessageIndustryModifyResponse response = alipayClient.execute(aliReq);
			if(response.isSuccess()){
				response.getParams();
			    return buildSuccessResp(new BaseResp());
			}
		} catch (AlipayApiException e)
		{
			e.printStackTrace();
		} 
		return buildInnerErrorResp(br);
//		Map<String, String> map = new HashMap<String, String>();
//		String orderInfo = OrderInfoUtil2_0.getOrderInfo(RSA_PRIVATE, PID, SELLER, subject, body, price);
//		map.put("status", ConstantInfo.RSC_SUCCESS);
//		map.put("info", ConstantInfo.RSS_SUCCESS);
//		map.put("alipaystr", orderInfo);
//		return map;
	}
	
	@RequestMapping("/alipay_notify")
	
	public void alipayNotify(HttpServletResponse resp)
	{
		//TODO
		//支付通知，此处可以更新订单状态，已付款等等
		
		resp.setCharacterEncoding("UTF-8");
		try
		{
			PrintWriter writer =  resp.getWriter();
			writer.write("success");			
		} catch (IOException e)
		{
			e.printStackTrace();
		}
	}
	
	@RequestMapping("/asd")
	@ResponseBody
	private Object asd(@RequestParam(value = "body") String body, HttpServletRequest request)
	{
		System.out.println(request.getHeader("User-Agent"));
		System.out.println(request.getParameter("body"));
		BaseResp br = new BaseResp();
		return buildSuccessResp(br);
	}

	/****
	 * 
	 * @param appId
	 *            应用ID
	 * @param pid
	 *            合作者身份ID（PID）是商户与支付宝签约后，商户获得的支付宝商户唯一识别码。当商户把支付宝功能接入商户网站时会用到PID，
	 *            以便让支付宝认证商户
	 * @param targetId
	 * @param request
	 * @param req
	 * @return
	 */
	// @RequestMapping("/getAuth2")
	// @ResponseBody
	// public Object getAuth2(@RequestParam(value = "appid") String appId,
	// @RequestParam(value = "pid") String pid,
	// @RequestParam(value = "target_id") String targetId,
	// HttpServletRequest request, HttpServletRequest req)
	// {
	//
	// Map<String, String> mapDefault = new HashMap<String, String>();
	// if (!TextUtils.isEmpty(appId) && !TextUtils.isEmpty(pid)
	// && !TextUtils.isEmpty(targetId))
	// {
	// Map<String, String> map = OrderInfoUtil2_0.buildOrderParamMap(appId);
	// Map<String, String> authInfoMap = OrderInfoUtil2_0
	// .buildAuthInfoMap(pid, appId, targetId);
	// String info = OrderInfoUtil2_0.buildOrderParam(authInfoMap);
	// String sign = OrderInfoUtil2_0.getSign(authInfoMap, RSA_PRIVATE);
	// String authInfo = info + "&" + sign;
	// map.put("status", ConstantInfo.RSC_SUCCESS);
	// map.put("info", ConstantInfo.RSS_SUCCESS);
	// map.put("alipaystr", authInfo);
	// return map;
	// } else
	// {
	// mapDefault.put("status", ConstantInfo.RSC_PARAM_INCOMPLETE);
	// mapDefault.put("info", ConstantInfo.RSS_PARAM_INCOMPLETE);
	// mapDefault.put("alipaystr", null);
	// return mapDefault;
	// }
	// }
}
